<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Channel;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class ChannelController extends AdminController
{

    protected $title = '渠道';
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Channel(), function (Grid $grid) {

            $grid->model()->with('logs');

            $grid->column('appid');
            $grid->column('chinese_sign', '中文标识');
            $grid->column('startup_count', '启动次数')->display(function () {
                return $this->logs()->count() ?? 0;
            });
            $grid->column('total_usage_seconds', '总计使用时长')->display(function () {
                $total_usage_seconds = $this->logs()->sum('usage_seconds');
                return ($total_usage_seconds) ? intval($total_usage_seconds / 60) . '分钟': 0;
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('appid');
            });

            $grid->disableQuickEditButton();
            $grid->disableViewButton();
            $grid->disableDeleteButton();
            $grid->toolsWithOutline(false);

            $grid->column('启动详情')->display(function () {
                $url = admin_url('channel_logs') . '?channel_id='. $this->id;
                return "<a href='$url'>跳转</a>";
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Channel(), function (Show $show) {
            $show->field('id');
            $show->field('appid');
            $show->field('chinese_sign');
            $show->field('startup_count');
            $show->field('total_usage_minutes');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Channel(), function (Form $form) {
            $form->display('id');
            $form->text('appid')->required();
            $form->text('chinese_sign', '中文标识')->required();

            $form->saving(function (Form $form) {

                if ($form->isCreating()) {

                    $channel_statistic = \App\Models\Channel::where('appid', $form->appid)->first();
                    if ($channel_statistic) {
                        return $form->response()->error('appid重复，请重新输入');
                    }
                }

            });
        });
    }
}
